package DCSource.Crypt;

import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class sSecurity {
	private Key key = null;
	private Cipher crypter = null;
	private Cipher decrypter = null;
	public sSecurity(){
		try{
			KeyGenerator kg = KeyGenerator.getInstance( "DES" );
			kg.init( 56 );
			key = kg.generateKey();
			crypter = Cipher.getInstance( "DES" );
			crypter.init( Cipher.ENCRYPT_MODE, key );
			decrypter = Cipher.getInstance( "DES" );
			decrypter.init( Cipher.DECRYPT_MODE, key );
		}catch(Exception err){
			
		}
	}
	public sSecurity(byte[] pw){
		try{
			if (pw.length<1){
				KeyGenerator kg = KeyGenerator.getInstance( "DES" );
				kg.init( 56 );
				key = kg.generateKey();
			}else{
				key = new SecretKeySpec(pw, "DES");
			}
			crypter = Cipher.getInstance( "DES" );
			crypter.init( Cipher.ENCRYPT_MODE, key );
			decrypter = Cipher.getInstance( "DES" );
			decrypter.init( Cipher.DECRYPT_MODE, key );
		}catch(Exception err){
			
		}
	}
	public Key getKey(){
		return key;
	}
	public byte[] encrypt(byte[] get) throws IllegalBlockSizeException, BadPaddingException{
		return crypter.doFinal(get);
	}
	public byte[] decrypt(byte[] get) throws IllegalBlockSizeException, BadPaddingException{
		return decrypter.doFinal(get);
	}
	public CipherOutputStream convertTo(OutputStream b){
		return new CipherOutputStream(b,crypter);
	}
	public CipherInputStream convertTo(InputStream b){
		return new CipherInputStream(b,decrypter);
	}
}
